import java.io.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.net.*;

class TCPServer
{

	public static void main(String argv[]) throws Exception
	{

		try
		{
		ServerSocket welcomeSocket = new ServerSocket(6606);


		while (true)
		{
			String Info=null;
			Socket ConnectionSocket = welcomeSocket.accept();
			BufferedReader inFromClient = new BufferedReader(new InputStreamReader(ConnectionSocket.getInputStream()));
			DataOutputStream outToClient = new DataOutputStream(ConnectionSocket.getOutputStream());
			Info=inFromClient.readLine();

			System.out.println("!!"+Info+"!!");			

			if(Info.startsWith("Q"))
			{
				new SThreadQuery(ConnectionSocket,Info).start();
			}
			else
			if(Info.startsWith("P"))
			{
				new SThreadPublish(ConnectionSocket).start();
			}
			else
			if(Info.startsWith("R"))
			{
				new SThreadRegister(ConnectionSocket,Info).start();
			}
			else
			{
				if(Info.startsWith("L"))
				{
					new SThreadLogin(ConnectionSocket,Info).start();
				}
				else
				if(Info.startsWith("C"))
				{
					new CPassThread(ConnectionSocket,Info).start();
				}
				else
					if(Info.startsWith("S"))
					{
						new SPassthread(ConnectionSocket,Info).start();
					}
					else
						if(Info.startsWith("O"))
						{
							new OlogThread(ConnectionSocket,Info).start();
						}
						else
							if(Info.startsWith("E"))
							{
								Calendar cal = Calendar.getInstance();
				        	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
								outToClient.writeBytes("E|"+ sdf.format(cal.getTime()) + "|" + '\n');
								outToClient.flush();
							}
							else
							{		
								outToClient.writeBytes("!|2| Message Received:"+ Info + '\n');
								outToClient.flush();
							}
			}
			

		}
		}
		catch(Exception e)
		{
			System.out.println("Socket already in use. A Server Process is already running.");
		}
	}
}
 